package fishBids.group3.behaviour.market;

import es.upm.agents.ontology.ToNotifyWinner;
import es.upm.agents.ontology.ToSellProduct;
import es.upm.agents.ontology.ToSellProductResponse;
import fishBids.group3.AgMarket;
import fishBids.group3.common.Constants;
import fishBids.group3.utils.Utils;
import jade.content.lang.Codec;
import jade.content.onto.Ontology;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.lang.acl.UnreadableException;

public class MarketBuyProductBehaviour extends CyclicBehaviour {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2472621384661749131L;
	
	public MarketBuyProductBehaviour(AgMarket agent, Codec codec, Ontology ontology){
		this.agMarket = agent;
		this.codec =  codec;
		this.ontology = ontology;
		
	}

	@Override
	public void action() {

		// Waits for estimation requests
		// Receive the message 
		ACLMessage msg = agMarket.receive(MessageTemplate.and(
				MessageTemplate.MatchPerformative(ACLMessage.INFORM),
				MessageTemplate.MatchProtocol(Constants.BUY_PRODUCT) )); 

		if (msg != null)

		{
			if (msg.getPerformative() == ACLMessage.INFORM) {

//					System.out.println( "Market >> Buy product inform message arrived, increasing time");
					
					ToNotifyWinner toNotifyWinner;
					try {
						toNotifyWinner = (ToNotifyWinner) msg.getContentObject();
						float itemCost = (Float)this.agMarket.getItemsPrices().get(toNotifyWinner.getProduct().getProductType().getType());
						
						float newItemCost =  itemCost + Utils.calculatePriceDelta( Constants.INCREASE_LOWER_LIMIT,
								Constants.INCREASE_UPPER_LIMIT, toNotifyWinner.getProduct().getAmount());
						
						this.agMarket.getItemsPrices().put(toNotifyWinner.getProduct().getProductType().getType(), new Float(newItemCost));
					} catch (UnreadableException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					

				}

		}else{
			block();
		}



	}
	
	AgMarket agMarket;
	Codec codec;
	Ontology ontology;

}
